#!/usr/bin/env python3
# coding:utf-8

"""
WIN系统计划任务管理模块
"""

__author__ = 'MC'


import sys
import traceback
import logging
from os import path
import getpass
import subprocess


class Task:

    def __init__(self):
        logging.basicConfig(format="%(asctime)s [%(levelname)s] [%(filename)s] %(message)s",
                            filename=path.split(path.realpath(__file__))[0] + "/Log/Error.log")

    def Create_Task(self, Name, Run, SC, MO, D, ST):
        """
        调用WIN系统命令schtasks创建计划任务
        :param Name: 计划任务名称
        :param Run: 运行的命令
        :param SC: 重复模式
        :param MO: 重复周期
        :param D: 周期内的某个时间
        :param ST: 开始时间
        :return: None
        """
        Command = "schtasks /Create /TN {0} /TR \"{1}\" /SC {2} /MO {3} /D {4} /ST {5}".format(Name, Run, SC, MO, D, ST)
        #print(Command)
        Task = subprocess.Popen(Command, stdout=subprocess.PIPE)
        StdOut = str(Task.stdout.read(), 'GBK')
        try:
           if StdOut.index("成功创建"):
               print("创建计划任务 {0} 成功".format(Name))
        except ValueError:
            print(StdOut)
        except Exception:
            print("系统错误：请查看程序目录下/Log/Error.log文件")
            E_Type, E_Value, E_TB = sys.exc_info()
            Trace_FileName, Trace_LineNo, Trace_FunName, Trace_Source = traceback.extract_tb(E_TB)[0]
            logging.error("[File:{0}] [LineNo:{1}] [Mes:{2}] [Source:{3}]".format(Trace_FileName, Trace_LineNo, E_Value, Trace_Source))

    def Delete_Task(self, TkName):
        """
        删除WIN计划任务
        :param TkName: 删除的计划任务名称
        :return:
        """
        Command = "schtasks /Delete /TN {0} /F".format(TkName)

        Task = subprocess.Popen(Command, stdout=subprocess.PIPE)
        StdOut = str(Task.stdout.read(), 'GBK')
        try:
            if StdOut.index("成功删除"):
               print("删除计划任务 {0} 成功".format(TkName))
        except ValueError:
            print(StdOut)
        except Exception:
            print("系统错误：请查看程序目录下/Log/Error.log文件")
            E_Type, E_Value, E_TB = sys.exc_info()
            Trace_FileName, Trace_LineNo, Trace_FunName, Trace_Source = traceback.extract_tb(E_TB)[0]
            logging.error("[File:{0}] [LineNo:{1}] [Mes:{2}] [Source:{3}]".format(Trace_FileName, Trace_LineNo, E_Value, Trace_Source))

    def Change_Task(self, TkName, ST):
        """
        修改WIN计划任务
        :param TkName: 更新的计划任务名称
        :param ST: 更新的开始时间
        :return:
        """

        # 执行命令前要获取用户的密码，以供系统命令使用
        Password = getpass.getpass("请输入用户密码(输入的密码不显示，正常输入即可):")
        Command = "schtasks /Change /TN {0} /ST {1} /RP {2}".format(TkName, ST, Password)
        Task = subprocess.Popen(Command, stdout=subprocess.PIPE)
        StdOut = str(Task.stdout.read(), 'GBK')
        try:
            if StdOut.index("更改了计划任务"):
               print("更新计划任务 {0} 成功".format(TkName))
        except ValueError:
            print(StdOut)
        except Exception:
            print("系统错误：请查看程序目录下/Log/Error.log文件")
            E_Type, E_Value, E_TB = sys.exc_info()
            Trace_FileName, Trace_LineNo, Trace_FunName, Trace_Source = traceback.extract_tb(E_TB)[0]
            logging.error("[File:{0}] [LineNo:{1}] [Mes:{2}] [Source:{3}]".format(Trace_FileName, Trace_LineNo, E_Value, Trace_Source))
